package com.api.sw.duban.action;

import com.alibaba.fastjson.JSONObject;
import com.api.browser.bean.SearchConditionGroup;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionFactory;
import com.api.browser.util.ConditionType;
import com.api.sw.duban.model.Assigned;
import com.api.sw.duban.model.FkTimejl;
import com.api.sw.duban.model.Uf_cbjlb;
import com.api.sw.duban.service.AssignedBaseService;
import com.api.sw.duban.service.FkTimeBaseService;
import com.api.sw.duban.service.Uf_cbjlbBaseService;
import com.api.sw.duban.util.BaseUtil;
import com.api.sw.duban.util.DubUtil;
import com.api.sw.duban.util.LogTool;
import com.api.sw.duban.util.SqlUtil;
import com.cloudstore.eccom.constant.WeaBoolAttr;
import com.cloudstore.eccom.pc.table.*;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.engine.core.interceptor.CommandContext;
import jxl.read.biff.Record;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.PageIdConst;
import weaver.general.Util;
import weaver.hrm.User;

import java.text.SimpleDateFormat;
import java.util.*;
/*
    立项签收
 */
public class DubanqsAction {
    private final static LogTool log = new LogTool("/log/duban/",false);
    public DubanqsAction(){

    };
    public JSONObject Dbjb(JSONObject param){
        JSONObject json=new JSONObject();
        SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String currentDate=sim.format(new Date());
        String mess="";
        boolean flag=true;
        String ckry="";
        if(param!=null){
            String bt="";//通知标题
            List<Object> list=new ArrayList<Object>();
            String rwid= Util.null2String(param.getString("rwid")).trim() ;//任务ID
            String userid= Util.null2String(param.getString("userid")).trim() ;//操作用户ID
            RecordSet re=new RecordSet();
            String sql ="select * from uf_dcsxzb where id='"+rwid+"' and isnull(zt,-1) in (-1,0)";//判断状态是否已经交办了
            re.execute(sql);
            if(re.next()){
                //判断数据创建人员是否就是当前操作人员
                bt=Util.null2String(re.getString("bt")).trim();//通知标题
                String modedatacreater=Util.null2String(re.getString("modedatacreater")).trim();//协办单位
                String zbdw=Util.null2String(re.getString("zbdw")).trim();//主办单位
                String xbdw=Util.null2String(re.getString("xbdw")).trim();//协办单位
                String jssx=Util.null2String(re.getString("xsjs")).trim();//接收时限
                String fksx=Util.null2String(re.getString("xsfk")).trim();//反馈时限
                String gzyq=Util.null2String(re.getString("gzyq")).trim();//工作要求
                String xbdwjsr=DubUtil.getDcryByReceiveunit(xbdw);//协办单位接收人
                ckry=xbdwjsr;
                if(!userid.equals(modedatacreater)){
                    flag=false;
                    mess="您没有交办次任务的权限";
                }else{
                    //开始交办
                    String[] zbdws=zbdw.split(",");
                    for(String str:zbdws){
                        str=Util.null2String(str).trim();
                        if("".equals(str)){
                           continue;
                        }
                        String zbdwjsr=Util.null2String(DubUtil.getDcryByReceiveunit(str)).trim();//协办单位接收人

                        if("".equals(zbdwjsr)){
                            continue;
                        }
                        ckry=ckry+zbdwjsr+",";
                        Assigned Assigned=new Assigned();
                        Assigned.setDjr(zbdwjsr);
                        Assigned.setDw(Util.getIntValue(str,-1));
                        Assigned.setFksx(fksx);
                        Assigned.setJssx(jssx);
                        Assigned.setZt(0);
                        Assigned.setSsrwid(rwid);
                        Assigned.setXbdjr(xbdwjsr);
                        Assigned.setZxb("0");
                        Assigned.setModeuuid(BaseUtil.getUUid());
                        Assigned.setYq(gzyq);
                        Assigned.setDbry(userid);
                        list.add(Assigned);
                    }
                }
                if(list.size()>0){
                    AssignedBaseService assignedBaseService=new AssignedBaseService();
                    mess=Util.null2String(assignedBaseService.getObjMapList(list,null)) ;
                    mess=setSxTime(rwid);
                    if("".equals(mess)){
                        //更新立项任务的状态
                        if(ckry.endsWith(",")){
                            ckry=ckry.substring(0,ckry.length()-1);
                        }
                        //re.execute("update uf_dcsxzb set zt='1',ckry='"+ckry+"',jbsj='"+currentDate+"' where id='"+rwid+"'");
                        re.execute("update uf_dcsxzb set zt='1',jbsj='"+currentDate+"' where id='"+rwid+"'");
                        //交办记录记录ID

                        List<String> var8 = Util.splitString2List(ckry, ",");
                        Set<String> ckrylist = new HashSet(var8);

                        if(ckrylist!=null&&ckrylist.size()>0){
                            log.writeLog("ckrylist"+ckrylist.toString());
                            String messtype=DubUtil.getMessgetype();
                            //int creater,String type ,Set<String> userIdList,String title,String context
                            if(!"".equals(messtype)){
                                DubUtil.SynSendMessage(1,messtype,ckrylist,"签收提醒","您有督办任务需要签收，请及时处理("+bt+")");
                            }

                        }
                    }else{
                        flag=false;
                    }
                }
            }else{
                flag=false;
                mess="您没有可以交办的数据请刷新页面";
            }
        }else{
            flag=false;
            mess="参数为空";
        }
        json.put("flag",flag);
        json.put("mess",mess);
        return json;
    }
    /*
        设置时限记录ID
     */
    public String setSxTime(String rwid){
        RecordSet re=new RecordSet();
        RecordSet re1=new RecordSet();
        String mess="";
        String sql="select * from uf_dbjblb where ssrwid='"+rwid+"'";
        re.execute(sql);
        List<Object> list=new ArrayList<Object>();
        FkTimejl  fkTimejl=null;
        while(re.next()){
            fkTimejl=new FkTimejl();
            String id=Util.null2String(re.getString("id"));
            String fksx=Util.null2String(re.getString("fksx"));//限时反馈
            fkTimejl.setFklx(0);
            fkTimejl.setJbjlid(id);
            fkTimejl.setFkyqsj(fksx);
            fkTimejl.setRwid(rwid);
            list.add(fkTimejl);

        }
        if(list.size()>0){
            FkTimeBaseService fkTimeBaseService=new FkTimeBaseService();
            mess=Util.null2String(fkTimeBaseService.getObjMapList(list,null)) ;
        }
        if(!"".equals(mess)){
            //删除 交办记录
            re1.execute("delete from uf_dbjblb where  ssrwid='"+rwid+"' and isnull(zt,-1) in (0,-1)");
        }
        return mess;
    }
    /*
        设置时限记录ID  用于补发
     */
    public String setSxTimeBybf(String rwid,String key1){
        RecordSet re=new RecordSet();
        RecordSet re1=new RecordSet();
        String mess="";
        String sql="select * from uf_dbjblb where key1='"+key1+"' and ssrwid='"+rwid+"'";
        re.execute(sql);
        List<Object> list=new ArrayList<Object>();
        FkTimejl  fkTimejl=null;
        while(re.next()){
            fkTimejl=new FkTimejl();
            String id=Util.null2String(re.getString("id"));
            String fksx=Util.null2String(re.getString("fksx"));//限时反馈
            fkTimejl.setFklx(0);
            fkTimejl.setJbjlid(id);
            fkTimejl.setFkyqsj(fksx);
            fkTimejl.setRwid(rwid);
            list.add(fkTimejl);

        }
        if(list.size()>0){
            FkTimeBaseService fkTimeBaseService=new FkTimeBaseService();
            mess=Util.null2String(fkTimeBaseService.getObjMapList(list,null)) ;
        }
        if(!"".equals(mess)){
            //删除 交办记录
            re1.execute("delete from uf_dbjblb where  ssrwid='"+rwid+"' and isnull(zt,-1) in (0,-1) and key1='"+key1+"'");
        }
        return mess;
    }
    /*
        任务签收 目前按照主任务的 的主办单位的对应负责人的权限进行签收
     */
    public JSONObject Dbqs(JSONObject param){
        JSONObject json=new JSONObject();
        String mess="";


        SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String currentDate=sim.format(new Date());
        boolean flag=true;
        if(param!=null){
            List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
            RecordSet re=new RecordSet();
            String DBType=re.getDBType();
            //log.writeLog("DBType"+DBType);
            String wrid=Util.null2String(param.getString("rwid"));
            if(wrid.endsWith(",")){
                wrid=wrid.substring(0,wrid.length()-1);
            }
            String userid=Util.null2String(param.getString("userid")).trim() ;
            Map<String, Object> SqlMap=null;
            if(!"".equals(userid)){
                String zwrid=Util.null2String(param.getString("zwrid"));
                if(zwrid.endsWith(",")){
                    zwrid=zwrid.substring(0,zwrid.length()-1);
                }
                String type=param.getString("type");
                if("0".equals(type)){//主任务

                    String sql="select * from uf_dbjblb where ssrwid in ("+wrid+") and isnull(zt,-1) in (-1,0) and ','+cast(djr as varchar(4000))+',' like '%,"+userid+",%'";
                    if(!"sqlserver".equals(DBType)){
                        sql="select * from uf_dbjblb where ssrwid in ("+wrid+") and isnull(zt,-1) in (-1,0) and ','||to_char(substr(djr,1,1000))||',' like '%,"+userid+",%'";
                    }
                    re.execute(sql);
                    while(re.next()){
                        String dataid=Util.null2String(re.getString("id")).trim() ;
                        Object[] obj=new Object[3];
                        obj[0]=1;
                        obj[1]=currentDate;
                        obj[2]=userid;
                        SqlMap=new HashMap<String, Object>();
                        SqlMap.put("sql","update uf_dbjblb set zt=?,sjjsrq=?,qsr=? where id="+dataid);
                        SqlMap.put("params",obj);
                        list.add(SqlMap);
                    }
                }else if("0".equals(type)){//子任务
                    String sql="select * from uf_dbjblb where id in ("+zwrid+") and isnull(zt,-1) in (-1,0) and ','||djr||',' like '%,"+userid+",%'";
                    if(!"sqlserver".equals(DBType)){
                        sql="select * from uf_dbjblb where id in ("+zwrid+") and isnull(zt,-1) in (-1,0) and ','||to_char(substr(djr,1,1000))||',' like '%,"+userid+",%'";
                    }
                    re.execute(sql);
                    while(re.next()){
                        String dataid=Util.null2String(re.getString("id")).trim() ;
                        Object[] obj=new Object[3];
                        obj[0]=1;
                        obj[1]=currentDate;
                        obj[2]=userid;
                        SqlMap=new HashMap<String, Object>();
                        SqlMap.put("sql","update uf_dbjblb set zt=?,sjjsrq=?,qsr=? where id="+dataid);
                        SqlMap.put("params",obj);
                        list.add(SqlMap);
                    }
                }
                if(list.size()>0){
                    flag= SqlUtil.executeUpdateListTran("local", list);
                    if(flag){
                        mess="更新异常!";
                    }
                }
            }else{
                mess="为获取用户请先登录";
                flag=false;
            }

        }
        json.put("flag",flag);
        json.put("mess",mess);
        return json;
    }
    //查询条件  文号 标题 编号
    public Map<String, Object> getQsTablelist(Map<String,Object> params, User user) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        if (null == user){
            apidatas.put("hasRight", false);
            return apidatas;
        }
        try {
            String wh=(String)Util.null2String(params.get("wh")) ;//文号
            String bt=(String)Util.null2String(params.get("bt")) ;//辩题
            String bh=(String)Util.null2String(params.get("bh")) ;//编号
            //返回消息结构体
            WeaResultMsg result = new WeaResultMsg(false);
            RecordSet re=new RecordSet();
            String DBType=re.getDBType();
            //log.writeLog("DBType"+DBType);
            String pageID = "17ecc14c-9d64-4a43-81a4-7b7c6f792857111";
            String pageUid = pageID + "_" + user.getUID();
            String pageSize = PageIdConst.getPageSize(pageID, user.getUID());

            String sqlwhere ="";
            if("sqlserver".equals(DBType)){
                sqlwhere=" 1=1 and isnull(a.zt,-1) in (1) and a.id in (select ssrwid from uf_dbjblb where ','+cast(djr as varchar(4000))+',' like '%,"+user.getUID()+",%' and isnull(zt,-1) in (-1,0)) ";
            }else{
                sqlwhere=" 1=1 and isnull(a.zt,-1) in (1) and a.id in (select ssrwid from uf_dbjblb where ','||to_char(substr(djr,1,1000))||',' like '%,"+user.getUID()+",%' and isnull(zt,-1) in (-1,0)) ";
            }

            if(!"".equals(wh)){
                sqlwhere=sqlwhere+" and a.wh like '%"+wh+"%'";
            }
            if(!"".equals(bt)){
                sqlwhere=sqlwhere+" and a.bt like '%"+bt+"%'";
            }
            if(!"".equals(bh)){
                sqlwhere=sqlwhere+" and a.bh like '%"+bh+"%'";
            }
            log.writeLog(sqlwhere);
            //新建一个weatable
            WeaTable table = new WeaTable();
            table.setTableType(WeaTableType.CHECKBOX);
            table.setPageUID(pageUid);
            table.setPageID(pageID);
            table.setPagesize(pageSize);

            String fileds = " a.*,'uf_dcsxzb' tablename,'sxlb' sxlbfield,'sxlbzl' sxlbzlfield,'hj' hjfield,a.xsjs xsjszt ";
            table.setBackfields(fileds);

            table.setSqlform(" uf_dcsxzb a");
            table.setSqlwhere(sqlwhere);
            table.setSqlorderby("id");
            table.setSqlprimarykey("id");
            table.setSqlisdistinct("false");

            table.getColumns().add(new WeaTableColumn("id").setDisplay(WeaBoolAttr.FALSE));   //设置为不显示
            table.getColumns().add(new WeaTableColumn("10%", "状态", "xsjszt","xsjszt","com.api.sw.duban.util.dubanTran.getQSStatus"));
            table.getColumns().add(new WeaTableColumn("20%", "编号", "bh","bh"));
            table.getColumns().add(new WeaTableColumn("30%", "标题", "bt","bt"));
            table.getColumns().add(new WeaTableColumn("20%", "接收部门", "zbdw","zbdw","com.api.sw.duban.util.dubanTran.getSwDpartmentnameByid"));
            WeaTableColumn sxlb=new WeaTableColumn("20%", "事项类别", "sxlb","sxlb","com.api.sw.duban.util.dubanTran.getSelectnameByValue");
            sxlb.setOtherpara("column:tablename").setOtherpara2("column:sxlbfield");
            table.getColumns().add(sxlb);
            //WeaTableColumn sxlbzl=new WeaTableColumn("20%", "子类", "sxlbzl","sxlbzl","com.api.sw.duban.util.dubanTran.getSelectnameByValue");
            //sxlbzl.setOtherpara("column:tablename").setOtherpara2("column:sxlbzlfield");
            //table.getColumns().add(sxlbzl);
            table.getColumns().add(new WeaTableColumn("20%", "限时签收", "xsjs","xsjs"));

            WeaTableColumn hj=new WeaTableColumn("10%", "缓急", "hj","hj","com.api.sw.duban.util.dubanTran.getSelectnameByValue");
            hj.setOtherpara("column:tablename").setOtherpara2("column:hjfield");
            table.getColumns().add(hj);
            table.getColumns().add(new WeaTableColumn("20%", "交办时间", "jbsj","jbsj"));
            table.getColumns().add(new WeaTableColumn("10%", "操作", "opter","opter"));
            table.getColumns().add(new WeaTableColumn("10%", "正文附件", "scfj","scfj","com.api.sw.duban.util.dubanTran.pingZwFj").setOtherpara("column:zw"));


            //增加右侧操作选项
            WeaTableOperates weaTableOperates = new WeaTableOperates();
            List<WeaTableOperate> operateList = new ArrayList<>();

            WeaTableOperate query = new WeaTableOperate("查看","","0");
            WeaTableOperate qs = new WeaTableOperate("签收","","1");

            operateList.add(query);
            operateList.add(qs);

            //设置check是否可用
            List<WeaTableCheckboxpopedom> checkboxpopedomList = new ArrayList<>();
            WeaTableCheckboxpopedom checkboxpopedom = new WeaTableCheckboxpopedom();
            checkboxpopedom.setPopedompara("column:id");
            checkboxpopedomList.add(checkboxpopedom);

            //table.setCheckboxList(checkboxpopedomList);
            table.setOperates(weaTableOperates);
            //weaTableOperates.setOperate(operateList);

            //table.setOperates(weaTableOperates);
            //table.setOperates(weaTableOperates);

            result.putAll(table.makeDataResult());
            result.put("hasRight", true);
            result.success();
            apidatas = result.getResultMap();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return apidatas;
    }
    public Map<String, Object> getCondition(Map<String,Object> params, User user) {

        Map<String, Object> apidatas = new HashMap<String, Object>();
        //角色判断参考代码
//        if(!HrmUserVarify.checkUserRight("LogView:View", user)){
//            apidatas.put("hasRight", false);
//            return apidatas;
//        }

        if (null == user){
            apidatas.put("hasRight", false);
            return apidatas;
        }

        apidatas.put("hasRight", true);

        /**
         * 高级搜索条件
         */
        ConditionFactory conditionFactory = new ConditionFactory(user);

        //条件组
        List<SearchConditionGroup> addGroups = new ArrayList<SearchConditionGroup>();

        List<SearchConditionItem> conditionItems = new ArrayList<SearchConditionItem>();

        //文本输入框
        SearchConditionItem wh = conditionFactory.createCondition(ConditionType.INPUT,502327, "wh");
        wh.setColSpan(2);//定义一行显示条件数，默认值为2,当值为1时标识该条件单独占一行
        wh.setFieldcol(16);	//条件输入框所占宽度，默认值18
        wh.setLabelcol(8);
        wh.setViewAttr(2);  //	 编辑权限  1：只读，2：可编辑， 3：必填   默认2
        wh.setLabel("文号"); //设置文本值  这个将覆盖多语言标签的值
        conditionItems.add(wh);


        //文本输入框
        SearchConditionItem bh = conditionFactory.createCondition(ConditionType.INPUT,502327, "bh");
        bh.setColSpan(2);//定义一行显示条件数，默认值为2,当值为1时标识该条件单独占一行
        bh.setFieldcol(16);	//条件输入框所占宽度，默认值18
        bh.setLabelcol(8);
        bh.setViewAttr(2);  //	 编辑权限  1：只读，2：可编辑， 3：必填   默认2
        bh.setLabel("编号"); //设置文本值  这个将覆盖多语言标签的值
        conditionItems.add(bh);

        //文本输入框
        SearchConditionItem bt = conditionFactory.createCondition(ConditionType.INPUT,502327, "bt");
        bt.setColSpan(2);//定义一行显示条件数，默认值为2,当值为1时标识该条件单独占一行
        bt.setFieldcol(16);	//条件输入框所占宽度，默认值18
        bt.setLabelcol(8);
        bt.setViewAttr(2);  //	 编辑权限  1：只读，2：可编辑， 3：必填   默认2
        bt.setLabel("标题"); //设置文本值  这个将覆盖多语言标签的值
        conditionItems.add(bt);

        addGroups.add(new SearchConditionGroup("查询条件",true,conditionItems));


        apidatas.put("condition",addGroups);

        return apidatas;

    }
    public JSONObject checkButton(Map<String,Object> params, User user){
        JSONObject json=new JSONObject();
        boolean flag=false;
        String rwid=Util.null2String(params.get("rwid")).trim() ;
        if(user==null||"".equals(Util.null2String(user.getUID()))||"".equals(rwid)){
            flag=false;
        }
        RecordSet re=new RecordSet();
        String DBType=re.getDBType();
        //log.writeLog("DBType"+DBType);

        String sql="select 1 from uf_dcsxzb where id='"+rwid+"' and  ISNULL(zt,-1) in (0,-1) and modedatacreater= "+user.getUID();
        re.execute(sql);
        if(re.next()){
            flag=true;
        }
        json.put("flag",flag);
        return json;
    }
    public  Map<String, Object> Urging(Map<String,Object> params, User user){
        Map<String, Object> json = new HashMap<String, Object>();
        String key=System.currentTimeMillis()+"";
        boolean flag=true;
        String mess="";
        Uf_cbjlb Uf_cbjlb=null;
        List<Object> list=new  ArrayList<Object>();
        String jbjlid=Util.null2String(params.get("jbjlid")).trim() ;
        String cbr=Util.null2String(params.get("cbr")).trim() ;
        String lxdh=Util.null2String(params.get("lxdh")).trim() ;
        String sm=Util.null2String(params.get("sm")).trim() ;
        log.writeLog(jbjlid+"Urging"+params.toString());
        if(user==null||"".equals(Util.null2String(user.getUID()))||"".equals(jbjlid)){
            mess="参数不合法!";
        }else{

            String[] jbjlids=jbjlid.split(",");
            for(String str:jbjlids){
                str= Util.null2String(str).trim() ;
                if("".equals(str)){
                    continue;
                }
                Uf_cbjlb=new Uf_cbjlb();
                Uf_cbjlb.setCbr(user.getUID()+"");
                Uf_cbjlb.setSm(sm);
                Uf_cbjlb.setLxdh(lxdh);
                Uf_cbjlb.setJbjlid(str);
                Uf_cbjlb.setKey1(key);
                Uf_cbjlb.setModedatacreater(user.getUID()+"");
                list.add(Uf_cbjlb);
            }
        }
        log.writeLog(list.toString());
        if(list.size()>0){
            Uf_cbjlbBaseService Uf_cbjlbBaseService=new Uf_cbjlbBaseService();
            mess= Uf_cbjlbBaseService.getObjMapList(list,null);
        }
        log.writeLog("mess"+mess);
        if(!"".equals(mess)){
            flag=false;
        }else{
            //授权
            ModeRightInfo mri=new ModeRightInfo();
            RecordSet re=new RecordSet();
            String sql="select * from uf_cbjlb where key='"+key+"' ";
            re.execute(sql);
            while(re.next()){
                int dataid=Util.getIntValue(re.getString("id"),-1);
                mri.editModeDataShare(user.getUID(),Util.getIntValue(new Uf_cbjlb().getFormmodeid(),0),dataid);
            }
        }
        json.put("flag",flag);
        json.put("mess",mess);
        return json;
    }
}
